from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
from django.db.models import Q, Count
from django.utils import timezone
from datetime import datetime, timedelta
from .models import SystemLog
from .serializers import SystemLogSerializer


class SystemLogListView(APIView):
    """系统日志列表视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取系统日志列表"""
        print("收到系统日志列表请求")

        try:
            # 检查权限 - 只有管理员可以访问
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id or user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 20))

            # 筛选参数
            action = request.GET.get('action', '')
            target_type = request.GET.get('target_type', '')
            user_filter = request.GET.get('user', '')
            start_date = request.GET.get('start_date', '')
            end_date = request.GET.get('end_date', '')
            ip_address = request.GET.get('ip_address', '')
            response_status = request.GET.get('response_status', '')
            search = request.GET.get('search', '')

            print(f"查询参数: action={action}, target_type={target_type}, user={user_filter}")

            # 构建查询条件
            queryset = SystemLog.objects.select_related('user').all()

            # 按操作类型筛选
            if action:
                queryset = queryset.filter(action__icontains=action)

            # 按目标类型筛选
            if target_type:
                queryset = queryset.filter(target_type=target_type)

            # 按用户筛选
            if user_filter:
                queryset = queryset.filter(
                    Q(user__username__icontains=user_filter) |
                    Q(user__real_name__icontains=user_filter)
                )

            # 按时间范围筛选
            if start_date:
                try:
                    start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
                    queryset = queryset.filter(created_at__gte=start_datetime)
                except ValueError:
                    pass

            if end_date:
                try:
                    end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
                    queryset = queryset.filter(created_at__lt=end_datetime)
                except ValueError:
                    pass

            # 按IP地址筛选
            if ip_address:
                queryset = queryset.filter(ip_address__icontains=ip_address)

            # 按响应状态筛选
            if response_status:
                try:
                    status_code = int(response_status)
                    queryset = queryset.filter(response_status=status_code)
                except ValueError:
                    pass

            # 搜索
            if search:
                queryset = queryset.filter(
                    Q(action__icontains=search) |
                    Q(description__icontains=search) |
                    Q(user__username__icontains=search) |
                    Q(user__real_name__icontains=search) |
                    Q(ip_address__icontains=search)
                )

            # 排序
            queryset = queryset.order_by('-created_at')

            # 计算总数
            total = queryset.count()

            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            logs = queryset[start:end]

            # 序列化数据
            serializer = SystemLogSerializer(logs, many=True)

            response_data = {
                'logs': serializer.data,
                'pagination': {
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': (total + page_size - 1) // page_size
                }
            }

            print(f"系统日志查询成功，共 {total} 条记录")

            return Response({
                'code': 200,
                'message': '获取系统日志列表成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"获取系统日志列表失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取系统日志列表失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class SystemLogDetailView(APIView):
    """系统日志详情视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request, log_id):
        """获取系统日志详情"""
        try:
            # 检查权限 - 只有管理员可以访问
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id or user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            try:
                log = SystemLog.objects.select_related('user').get(id=log_id)
            except SystemLog.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '日志记录不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            serializer = SystemLogSerializer(log)

            return Response({
                'code': 200,
                'message': '获取日志详情成功',
                'data': serializer.data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"获取日志详情失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取日志详情失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class SystemLogStatsView(APIView):
    """系统日志统计视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取系统日志统计数据"""
        try:
            # 检查权限 - 只有管理员可以访问
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id or user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取时间范围参数
            days = int(request.GET.get('days', 7))  # 默认最近7天
            end_date = timezone.now()
            start_date = end_date - timedelta(days=days)

            # 基础统计
            total_logs = SystemLog.objects.count()
            recent_logs = SystemLog.objects.filter(created_at__gte=start_date).count()

            # 成功和失败请求统计
            success_logs = SystemLog.objects.filter(
                created_at__gte=start_date,
                response_status__gte=200,
                response_status__lt=400
            ).count()

            error_logs = SystemLog.objects.filter(
                created_at__gte=start_date,
                response_status__gte=400
            ).count()

            # 操作类型统计（最近时间范围内）
            action_stats = SystemLog.objects.filter(
                created_at__gte=start_date
            ).values('action').annotate(
                count=Count('id')
            ).order_by('-count')[:10]

            # 目标类型统计
            target_type_stats = SystemLog.objects.filter(
                created_at__gte=start_date,
                target_type__isnull=False
            ).values('target_type').annotate(
                count=Count('id')
            ).order_by('-count')

            # 用户活动统计（前10名）
            user_activity_stats = SystemLog.objects.filter(
                created_at__gte=start_date,
                user__isnull=False
            ).values(
                'user__username', 'user__real_name', 'user__role'
            ).annotate(
                count=Count('id')
            ).order_by('-count')[:10]

            # 每日日志数量统计
            daily_stats = []
            for i in range(days):
                date = start_date + timedelta(days=i)
                next_date = date + timedelta(days=1)

                daily_count = SystemLog.objects.filter(
                    created_at__gte=date,
                    created_at__lt=next_date
                ).count()

                daily_stats.append({
                    'date': date.strftime('%Y-%m-%d'),
                    'count': daily_count
                })

            # 每小时统计（最近24小时）
            hourly_stats = []
            now = timezone.now()
            for i in range(24):
                hour_start = now - timedelta(hours=23 - i)
                hour_start = hour_start.replace(minute=0, second=0, microsecond=0)
                hour_end = hour_start + timedelta(hours=1)

                hourly_count = SystemLog.objects.filter(
                    created_at__gte=hour_start,
                    created_at__lt=hour_end
                ).count()

                hourly_stats.append({
                    'hour': hour_start.strftime('%H:00'),
                    'count': hourly_count
                })

            # 响应状态统计
            status_stats = []
            status_ranges = [
                (200, 299, '2xx 成功'),
                (300, 399, '3xx 重定向'),
                (400, 499, '4xx 客户端错误'),
                (500, 599, '5xx 服务器错误')
            ]

            for start_status, end_status, label in status_ranges:
                count = SystemLog.objects.filter(
                    created_at__gte=start_date,
                    response_status__gte=start_status,
                    response_status__lte=end_status
                ).count()

                if count > 0:
                    status_stats.append({
                        'status_range': label,
                        'count': count
                    })

            # IP地址统计（前10名）
            ip_stats = SystemLog.objects.filter(
                created_at__gte=start_date,
                ip_address__isnull=False
            ).values('ip_address').annotate(
                count=Count('id')
            ).order_by('-count')[:10]

            response_data = {
                'basic_stats': {
                    'total_logs': total_logs,
                    'recent_logs': recent_logs,
                    'success_logs': success_logs,
                    'error_logs': error_logs,
                    'success_rate': round(success_logs / max(recent_logs, 1) * 100, 2)
                },
                'charts': {
                    'daily_logs': daily_stats,
                    'hourly_logs': hourly_stats,
                    'action_distribution': list(action_stats),
                    'target_type_distribution': list(target_type_stats),
                    'status_distribution': status_stats
                },
                'rankings': {
                    'user_activity': list(user_activity_stats),
                    'ip_activity': list(ip_stats)
                },
                'time_range': {
                    'start_date': start_date.strftime('%Y-%m-%d %H:%M:%S'),
                    'end_date': end_date.strftime('%Y-%m-%d %H:%M:%S'),
                    'days': days
                }
            }

            return Response({
                'code': 200,
                'message': '获取日志统计数据成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"获取日志统计数据失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取日志统计数据失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class SystemLogBatchDeleteView(APIView):
    """系统日志批量删除视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def delete(self, request):
        """批量删除系统日志"""
        try:
            # 检查权限 - 只有管理员可以访问
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id or user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取删除参数
            delete_type = request.data.get('type')  # 'ids', 'date_range', 'all'

            if delete_type == 'ids':
                # 按ID批量删除
                ids = request.data.get('ids', [])
                if not ids:
                    return Response({
                        'code': 400,
                        'message': '请选择要删除的日志记录'
                    }, status=status.HTTP_400_BAD_REQUEST)

                deleted_count = SystemLog.objects.filter(id__in=ids).delete()[0]

            elif delete_type == 'date_range':
                # 按时间范围删除
                start_date = request.data.get('start_date')
                end_date = request.data.get('end_date')

                if not start_date:
                    return Response({
                        'code': 400,
                        'message': '请指定开始日期'
                    }, status=status.HTTP_400_BAD_REQUEST)

                try:
                    start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
                    queryset = SystemLog.objects.filter(created_at__gte=start_datetime)

                    if end_date:
                        end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
                        queryset = queryset.filter(created_at__lt=end_datetime)

                    deleted_count = queryset.delete()[0]

                except ValueError:
                    return Response({
                        'code': 400,
                        'message': '日期格式错误'
                    }, status=status.HTTP_400_BAD_REQUEST)

            elif delete_type == 'all':
                # 删除所有日志（保留最近7天）
                keep_days = request.data.get('keep_days', 7)
                cutoff_date = timezone.now() - timedelta(days=keep_days)
                deleted_count = SystemLog.objects.filter(created_at__lt=cutoff_date).delete()[0]

            else:
                return Response({
                    'code': 400,
                    'message': '无效的删除类型'
                }, status=status.HTTP_400_BAD_REQUEST)

            print(f"批量删除日志成功，删除了 {deleted_count} 条记录")

            return Response({
                'code': 200,
                'message': f'成功删除 {deleted_count} 条日志记录',
                'data': {'deleted_count': deleted_count}
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"批量删除日志失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '批量删除日志失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class SystemLogExportView(APIView):
    """系统日志导出视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """导出系统日志"""
        try:
            # 检查权限 - 只有管理员可以访问
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id or user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取导出参数
            export_format = request.data.get('format', 'csv')  # csv, json
            start_date = request.data.get('start_date')
            end_date = request.data.get('end_date')
            filters = request.data.get('filters', {})

            # 构建查询条件
            queryset = SystemLog.objects.select_related('user').all()

            # 应用时间范围
            if start_date:
                try:
                    start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
                    queryset = queryset.filter(created_at__gte=start_datetime)
                except ValueError:
                    pass

            if end_date:
                try:
                    end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
                    queryset = queryset.filter(created_at__lt=end_datetime)
                except ValueError:
                    pass

            # 应用其他筛选条件
            if filters.get('action'):
                queryset = queryset.filter(action__icontains=filters['action'])
            if filters.get('target_type'):
                queryset = queryset.filter(target_type=filters['target_type'])
            if filters.get('user'):
                queryset = queryset.filter(
                    Q(user__username__icontains=filters['user']) |
                    Q(user__real_name__icontains=filters['user'])
                )

            # 限制导出数量（避免数据过大）
            max_records = 10000
            if queryset.count() > max_records:
                return Response({
                    'code': 400,
                    'message': f'导出数据过多，请缩小查询范围（当前 {queryset.count()} 条，最多 {max_records} 条）'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 获取数据
            logs = queryset.order_by('-created_at')

            # 序列化数据
            serializer = SystemLogSerializer(logs, many=True)

            # 生成导出文件名
            timestamp = timezone.now().strftime('%Y%m%d_%H%M%S')
            filename = f"system_logs_{timestamp}.{export_format}"

            if export_format == 'csv':
                # CSV 格式导出
                import csv
                import io

                output = io.StringIO()
                writer = csv.writer(output)

                # 写入表头
                headers = [
                    'ID', '操作用户', '操作类型', '操作描述', '目标类型', '目标ID',
                    'IP地址', '响应状态', '操作时间'
                ]
                writer.writerow(headers)

                # 写入数据
                for log_data in serializer.data:
                    row = [
                        log_data['id'],
                        log_data.get('user_name', ''),
                        log_data['action'],
                        log_data.get('description', ''),
                        log_data.get('target_type', ''),
                        log_data.get('target_id', ''),
                        log_data.get('ip_address', ''),
                        log_data.get('response_status', ''),
                        log_data['created_at']
                    ]
                    writer.writerow(row)

                csv_content = output.getvalue()
                output.close()

                return Response({
                    'code': 200,
                    'message': '导出成功',
                    'data': {
                        'filename': filename,
                        'content': csv_content,
                        'content_type': 'text/csv',
                        'record_count': len(serializer.data)
                    }
                }, status=status.HTTP_200_OK)

            elif export_format == 'json':
                # JSON 格式导出
                import json

                export_data = {
                    'export_info': {
                        'timestamp': timezone.now().isoformat(),
                        'record_count': len(serializer.data),
                        'filters': filters
                    },
                    'logs': serializer.data
                }

                json_content = json.dumps(export_data, ensure_ascii=False, indent=2)

                return Response({
                    'code': 200,
                    'message': '导出成功',
                    'data': {
                        'filename': filename,
                        'content': json_content,
                        'content_type': 'application/json',
                        'record_count': len(serializer.data)
                    }
                }, status=status.HTTP_200_OK)

            else:
                return Response({
                    'code': 400,
                    'message': '不支持的导出格式'
                }, status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            print(f"导出日志失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '导出日志失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)